package com.open.pokergames.comm.user

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import cn.sinothk.hussars.data.CodeValue
import com.bumptech.glide.Glide
import com.open.pokergames.NetConfig
import com.open.pokergames.R
import com.open.pokergames.base.activity.EventBusTitleBaseActivity
import com.open.pokergames.comm.repository.cache.LocalCache
import com.open.pokergames.comm.repository.entity.*
import com.open.pokergames.comm.repository.viewModel.SystemViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.helper.image.compress.ImageCompress
import com.sinothk.image.selector.PhotoPickerActivity
import com.sinothk.image.selector.SelectModel
import com.sinothk.image.selector.intent.PhotoPickerIntent
import com.sinothk.view.image.crop.CropImageMainActivity
import kotlinx.android.synthetic.main.activity_user_edit.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

open class UserEditActivity : EventBusTitleBaseActivity(), View.OnClickListener {

    var viewModel: SystemViewModel? = null
    private var userVo: UserVo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_edit)
        setViewTitle("编辑信息")
        initView()
        setListener()
        viewModel = SystemViewModel()

    }

    private fun initView() {
        val loginUser = LocalCache.getUser()
        userVo = UserVo()
        userVo!!.id = loginUser.id
        userNameEt.setText(XUtils.string().getNotNullValue(loginUser.userName, "未知"))
        phoneEt.setText(XUtils.string().getNotNullValue(loginUser.phoneNum, "未知"))

        Glide.with(this).load(NetConfig.getImageUrl(loginUser.userAvatar))
            .placeholder(R.drawable.default_img)
            .error(R.drawable.default_img)
            .into(imageView)
    }

    private fun setListener() {
        avatarItem.setOnClickListener(this)
        doBtn.setOnClickListener(this)
    }


    override fun onClick(v: View) {
        when (v) {
            avatarItem -> {
                updateAvatar(this)
            }
            doBtn -> {
                submit()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun avatarCallback(resultInfo: ResultInfo<LoginDto>) {

//        if (resultInfo.eventType != "register") {
//            return
//        }
//
//        when (resultInfo.code) {
//            ResultInfo.SUCCESS -> {
//                LocalCache.setLoginUser(resultInfo.data)
//                LocalCache.setAutoLogin(true)
//                XUtils.intent().openActivity(this@RegisterActivity, MainActivity::class.java)
//                    .finish(true).start()
//            }
//            else -> {
//                XUtils.toast().show(resultInfo.msg)
//            }
//        }
    }

    private fun updateAvatar(activity: FragmentActivity) {
        val intent = PhotoPickerIntent(activity)
        intent.setSelectModel(SelectModel.SINGLE)//  SelectModel.SINGLE
        intent.setShowCamera(true, activity.application.packageName) // 是否显示拍照， 默认false com.sinothk.living
        startActivityForResult(intent, CodeValue.IMG_SELECT_CODE)
    }

    private var avatarPath = ""

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (data == null) {
            return
        }

        // 图片选择
        if (requestCode == CodeValue.IMG_SELECT_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val filePathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)

                if (filePathList != null && filePathList.size > 0) {
                    val imageFilePath = filePathList[0]
                    val oldFile = File(imageFilePath)
                    val fileSize = oldFile.length()

                    val mb = 0.5 * 1024 * 1024
                    if (fileSize > mb) {// 大于0.5MB压缩
                        ImageCompress.execute(imageFilePath) { obj, _ ->
                            if (obj != null) {

                                val newPath: String = obj as String
                                val newFile = File(newPath)
                                if (newFile.length() > 0) {
                                    cutImage(newPath)
                                } else {
                                    XUtils.toast().show("压缩图片为空")
                                }
                            } else {
                                XUtils.toast().show("图片压缩失败")
                            }
                        }
                    } else {
                        if (oldFile.length() > 0) {
                            cutImage(imageFilePath)
                        } else {
                            XUtils.toast().show("选择的文件太小")
                        }
                    }
                } else {
                    XUtils.toast().show("选择图片失败")
                }
            }
            return
        }

        // 图片剪切
        if (requestCode == CodeValue.IMG_CROP_CODE) {
            when (resultCode) {
                -1 -> {
                    avatarPath = data.getStringExtra("cropImagePath") as String
                    doUploadFile(avatarPath)
                }
                -100 -> XUtils.toast().show("取消图片剪切")
                else -> XUtils.toast().show("图片剪切未知错误")
            }
            return
        }
    }

    private fun cutImage(filePath: String) {
        CropImageMainActivity.start(this, filePath, CodeValue.IMG_CROP_CODE, CropImageMainActivity.STYLE_4)
    }

    private fun doUploadFile(filePath: String) {
        showLoadingDialog("正在上传")
        viewModel?.uploadFile("sys", filePath)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveUploadFileEventBus(resultInfo: ResultInfo<FileEntity>) {

        if ("uploadFile" != resultInfo.eventType) {
            return
        }

        hideLoadingDialog()

        when (resultInfo.code) {
            ResultInfo.SUCCESS -> {

                val url = resultInfo.data.fileUrl
                if (XUtils.string().isNotEmpty(url)) {
                    Glide.with(this).load(NetConfig.getImageUrl(url.replace("\\", "/")))
                        .placeholder(R.drawable.default_img)
                        .error(R.drawable.default_img)
                        .into(imageView)
                    userVo!!.userAvatar = url
                } else {

                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(resultInfo.msg)
            }
        }
    }

    private fun submit() {
        val name = userNameEt.text.toString()
        val phone = phoneEt.text.toString()

        if (XUtils.string().isEmpty(name)) {
            XUtils.toast().show("用户名称不能为空")
            return
        }
        if (XUtils.string().isEmpty(phone)) {
            XUtils.toast().show("手机号码不能为空")
            return
        }
//        if (XUtils.string().isEmpty(userVo?.sex)) {
//            XUtils.toast().show("请选择用户性别")
//            return
//        }

        userVo!!.userName = name
        userVo!!.phoneNum = phone
        showLoadingDialog("正在提交")
        viewModel!!.editUser(userVo!!)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun editCallback(resultInfo: ResultInfo<UserEntity>) {

        if (resultInfo.eventType != "editUser") {
            return
        }
        hideLoadingDialog()
        when (resultInfo.code) {
            ResultInfo.SUCCESS -> {
                LocalCache.setUser(resultInfo.data)
                finish()
            }
            else -> {
                XUtils.toast().show(resultInfo.msg)
            }
        }
    }
}